package middleware

import (
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"net/http"
)

func AuthUserMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("token")
		if token == "" {
			c.JSON(http.StatusNotFound, gin.H{
				"code":    10001,
				"message": "token is nil",
			})
			c.Abort()
			return
		}

		nreJwt := jwt.NewJWT("Token")
		claims, err := nreJwt.ParseToken(token)
		if err != nil {
			c.JSON(http.StatusNotFound, gin.H{
				"code":    10001,
				"message": "token is invalid",
			})
			c.Abort()
			return
		}

		userId := claims.ID
		c.Set("userId", userId)
		c.Next()
	}
}
